package lab2;
/*  $Id: Lab2.java
 *  
 *  Copyright 2012, The Johns Hopkins University Whiting School of Engineering
 *  All rights reserved.
 *  This material may be used, modified and reproduced by faculty,
 *  staff, and students of The Johns Hopkins University for instruction, 
 *  evaluation, and grading purposes.  For any other permission, please 
 *  contact The Johns Hopkins University Whiting School of Engineering.
 */

import java.math.*;

/**
*  Lab1 2: Main Class
*  @date       15JULY2012
*  @author     Michael W. Mathes
*
* 
* @Source Reference: 
* Khan, Salman. "Linear Algebra: Nxn Determinant: Defining the Determinant for 
* Nxn Matrices. An Exampled of a 4x4 Determinant." 
* Khan Academy. Khan Academy, n.d. Web. 14 July 2012. 
* <http://www.khanacademy.org/math/linear-algebra/v/linear-algebra--nxn-determinant>.
* 
*/
 
public class calcDet {
  public int det(int[][] matrix){
    int result = 0;
    int order = matrix.length;
    
    // The determinant of a 1x1 matrix is simply the matrix itself
    if (order ==1){
      result = matrix[0][0];
    }
    
    // the determimant of a 2x2 matrix is defined as det(A) = ad-bc
    if (order ==2){
        result = matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0];
    }
    
    // for orders >2 we use recurrison to speed things along 
    if (order >2){
      for (int i =0; i<order; i++){
      //create minor where x is not 1, and y is not i
      int[][] minor =new int[order-1][order-1];
      
      for(int j = 1; j < matrix.length; j++) {
        System.arraycopy(matrix[j], 0, minor[j-1], 0, i);
        System.arraycopy(matrix[j], i+1, minor[j-1], i, matrix[0].length-i-1);
        }
      
      
      //recursion           
      result = result + matrix[0][i]*(int)Math.pow(-1,(double)i)* det(minor);    
      }
    }
    
    
    return result;

  
  }//end-ded 
}//end-class
